let dao = require('../database/dao'),
  logger = require('../helper/logger'),
  tagLogger = new logger.TagLogger('POLL_MODEL'),
  errorCode = require('../../conf/errorCode'),
  commonModel = require('./commonModel'),
  util = require('../helper/util'),
  _ = require('lodash');

let {
  genUpdateCallback,
  genInsertCallback,
  genUpdateRslt,
  genUpdateBatchRslt,
  genUpdateBatchCallback,
  genSelectCallback,
  genPagination,
  genInertRslt,
} = commonModel;

//根据pollId获取投票信息
var getPollRelByPollId = (exports.getPollRelByPollId = function(
  pollId,
  callback,
) {
  dao.all(
    `SELECT poll_choices.id choiceId,poll_choices.title ,poll_choices.img,
                COUNT(poll_answers.id) * 100 / (
                    SELECT COUNT(*)
                        FROM poll_answers
                            WHERE poll_answers.poll_id = ?) AS percentage
                            FROM poll_choices
                            LEFT JOIN poll_answers
                            ON poll_choices.id = poll_answers.choice_id
                            WHERE poll_choices.poll_id = ?
                            GROUP BY poll_choices.id`,
    [pollId, pollId],
    callback,
  );
});

//根据postId获取投票信息
var getPollDetailByPostId = (exports.getPollDetailByPostId = function(
  postId,
  callback,
) {
  dao.all(
    `SELECT id pollId,question,startAt,endAt
                            FROM polls where postId = ?`,
    [postId],
    callback,
  );
});

//根据pollId获取选票信息
var getPollChoiceByPollId = (exports.getPollChoiceByPollId = function(
  pollId,
  callback,
) {
  dao.all(
    `SELECT c.id choiceId,c.title,c.img
                            FROM poll_choices c
                                where c.poll_id = ?`,
    [pollId],
    callback,
  );
});

//插入投票
var add = (exports.add = async function(pollObj, pollChoiceObj, callback) {
  let rel = await util.promiseify(dao.insert)('polls', pollObj),
    pollId = rel.insertId,
    queryArr = [];
  for (let i = 0, len = pollChoiceObj.length; i < len; i++) {
    pollChoiceObj[i].poll_id = pollId;
    let query = {
      str: `insert into poll_choices set ?`,
      param: [pollChoiceObj[i]],
    };
    queryArr.push(query);
  }
  dao.queryBatch(queryArr, callback);
});

